<template>
  <div class="container">
    <el-row class="top-row">
      <el-col :span="3" class="search-container">
        <el-input v-model="keyword" placeholder="模糊查询" size="small" />
      </el-col>
      <el-col :span="1">
        <el-button
          v-show="permisson.hasAdd"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="openInsertForm"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="23">
        <el-table
          v-loading="isLoad"
          class="table-row"
          size="mini"
          :data="users"
        >
          <el-table-column label="帐号" align="center" prop="username" />
          <el-table-column label="姓名" align="center" prop="cnname" />
          <el-table-column label="部门" align="center" prop="depid.deptname" />
          <el-table-column label="用户级别" align="center">
            <template slot-scope="{ row }">
              <template v-if="row.llevel === 1"> 普通员工 </template>
              <template v-else-if="row.llevel === 2">
                部门级系统管理员
              </template>
              <template v-else> 公司级系统管理员 </template>
            </template>
          </el-table-column>

          <el-table-column label="手机号" align="center" prop="mobile" />
          <el-table-column label="qq号" align="center" prop="QQ" />
          <el-table-column align="center" label="操作" width="300px">
            <template slot-scope="{ row }">
              <el-button
                v-show="permisson.hasUpdate"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="openUpdateForm(row)"
              >
                修改
              </el-button>
              <el-button
                v-show="permisson.hasDelete"
                icon="el-icon-delete"
                type="danger"
                size="mini"
                @click="deleteRow(row)"
              >
                删除
              </el-button>
              <el-dropdown :hide-on-click="false">
                <el-button size="mini" type="info" style="margin-left: 10px">
                  更多 >
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item @click.native="openDetail(row)">
                    详情
                  </el-dropdown-item>

                  <el-popover
                    placement="left"
                    title="角色"
                    width="200"
                    trigger="hover"
                    @show="openRoleList(row)"
                  >
                    <template v-if="roleList.isLoad">
                      <i class="el-icon-loading" />
                      载入中...
                    </template>
                    <template v-else>
                      <el-tag
                        v-for="(item, index) in roleList.data"
                        :key="index"
                        size="small"
                        effect="dark"
                        class="role-tag"
                      >
                        {{ item.rolename }}
                      </el-tag>
                      <span v-if="roleList.data.length === 0">
                        没有任何角色
                      </span>
                    </template>
                    <el-dropdown-item slot="reference"> 角色 </el-dropdown-item>
                  </el-popover>

                  <el-popover
                    placement="left"
                    title="用户组"
                    width="200"
                    trigger="hover"
                    @show="openUserGroupList(row)"
                  >
                    <template v-if="groupList.isLoad">
                      <i class="el-icon-loading" />
                      载入中...
                    </template>
                    <template v-else>
                      <el-tag
                        v-for="(item, index) in groupList.data"
                        :key="index"
                        size="small"
                        effect="dark"
                        class="role-tag"
                      >
                        {{ item.emgname }}
                      </el-tag>
                      <span v-if="groupList.data.length === 0">
                        没有属于任何用户组
                      </span>
                    </template>
                    <el-dropdown-item slot="reference">
                      用户组
                    </el-dropdown-item>
                  </el-popover>
                  <el-dropdown-item @click.native="openPlatForm(row)">
                    平台
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="unlockRow(row)">
                    解锁
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="top-row">
      <el-col :span="20">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="size"
          :current-page.sync="page"
        />
      </el-col>

      <el-col :span="2" class="page-size-container">
        <el-select v-model="size" placeholder="页大小" size="small">
          <el-option
            v-for="(item, index) in sizeList"
            :key="index"
            :label="item + '条/页'"
            :value="item"
          />
        </el-select>
      </el-col>
      <el-col :span="2" class="page-total-container">
        总 {{ total }} 条
      </el-col>
    </el-row>

    <el-dialog
      title="📝修改"
      :visible.sync="edit.show"
      width="50%"
      :before-close="formClose"
    >
      <user-form
        ref="updateForm"
        :data="edit.target"
        @submit="updateFormSubmit"
      />

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="edit.show = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="checkUpdateForm"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="📝新增"
      :visible.sync="addit.show"
      width="50%"
      :before-close="formClose"
    >
      <user-form
        ref="insertForm"
        :data="addit.target"
        is-create
        @submit="insertFormSubmit"
      />

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="addit.show = false">取 消</el-button>
        <el-button type="primary" size="medium" @click="checkInsertForm">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="📄详情"
      :visible.sync="detail.show"
      width="20%"
      :before-close="formClose"
    >
      <el-form label-width="110px" size="mini">
        <el-form-item label="帐号:">
          <div style="font-weight: 600">
            {{ detail.target.username }}
          </div>
        </el-form-item>

        <el-form-item label="姓名:">
          <div style="font-weight: 600">
            {{ detail.target.cnname }}
          </div>
        </el-form-item>

        <el-form-item label="部门:">
          <div style="font-weight: 600">
            {{ detail.target.depid.deptname }}
          </div>
        </el-form-item>
        <el-form-item label="用户级别:">
          <div style="font-weight: 600">
            <template v-if="detail.target.llevel === 1"> 普通员工 </template>
            <template v-else-if="detail.target.llevel === 2">
              部门级系统管理员
            </template>
            <template v-else> 公司级系统管理员 </template>
          </div>
        </el-form-item>

        <el-form-item label="手机号:">
          <div style="font-weight: 600">
            {{ detail.target.mobile || "无" }}
          </div>
        </el-form-item>

        <el-form-item label="QQ:">
          <div style="font-weight: 600">
            {{ detail.target.QQ || "无" }}
          </div>
        </el-form-item>

        <el-form-item label="微信:">
          <div style="font-weight: 600">
            {{ detail.target.wxcode || "无" }}
          </div>
        </el-form-item>

        <el-form-item label="备注:">
          <div style="font-weight: 600">
            {{ detail.target.remark || "无" }}
          </div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer" />
    </el-dialog>

    <el-dialog
      title="🛠平台"
      :visible.sync="platForm.show"
      width="30%"
      :before-close="formClose"
    >
      <el-table
        :data="platForm.data"
        border
        highlight-current-row
        :show-header="false"
        max-height="600"
        style="width: 100%"
        @current-change="handleChangePlatSelected"
      >
        <el-table-column prop="alarmobjtype" label="名称" />
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="platForm.show = false"
          >取 消</el-button
        >
        <el-button type="primary" size="medium" @click="platFormSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { HTTP_OK } from "@/api/constants";
import {
  getUsersData,
  getUserDetail,
  deleteUser,
  getUserRoles,
  getUserGroup,
  getPlatList,
  updateUser,
  unlockUser,
  insertUser,
  createPlatUser,
} from "@/api/system-manage/user";
import { OperationType, recordOperateLogFunc } from "@/api/log";
import UserForm from "./UserForm.vue";
import { userPermisson } from "./perm";

const recordOperateLog = recordOperateLogFunc("系统管理", "用户管理");

export default {
  components: { UserForm },
  data() {
    return {
      // 用户数据
      users: [],
      // 是否处于加载
      isLoad: true,
      // 总数
      total: 0,
      // 页数
      page: 1,
      // 每页大小
      size: 15,
      // 搜索关键词
      keyword: "",
      // 每页大小候选项
      sizeList: [10, 15, 20, 30, 40, 50],

      // 防抖计时器
      keywordTimer: setTimeout(() => {}, 555),

      // 修改窗口状态
      edit: {
        // 显示
        show: false,
        // 修改的目标数据
        target: {},
      },

      // 新增窗口状态
      addit: {
        show: false,
        target: {},
      },

      // 详情窗口状态
      detail: {
        show: false,
        target: {
          username: "",
          depid: {},
          mobile: "",
          wxcode: "",
          QQ: "",
          cnname: "",
          llevel: 1,
          remark: "",
          password: "",
        },
      },

      // 角色列表
      roleList: {
        isLoad: true,
        data: [],
      },

      // 用户组列表
      groupList: {
        isLoad: true,
        data: [],
      },

      // 平台表单
      platForm: {
        show: false,
        target: {},
        selected: {},
        data: [],
      },

      permisson: {
        hasAdd: false,
        hasUpdate: false,
        hasDelete: false,
        hasSelect: false,
      },
    };
  },
  watch: {
    page() {
      this.refreshUserList();
    },
    size() {
      this.refreshUserList();
    },
    keyword() {
      this.$data.isLoad = true;
      // 页数置为1
      this.$data.page = 1;
      // 计时器防抖
      clearTimeout(this.$data.keywordTimer);
      this.$data.keywordTimer = setTimeout(this.refreshUserList, 555);
    },
  },
  mounted() {
    this.$data.permisson = userPermisson();

    this.refreshUserList();
    this.initPlatList();
  },

  methods: {
    /**
     * 初始化平台列表
     */
    async initPlatList() {
      const { detail } = await getPlatList();
      this.$data.platForm.data = detail;
      recordOperateLog(OperationType.Select, "平台");
    },
    async refreshUserList() {
      if (this.$data.permisson.hasSelect === false) {
        this.$message.warning("没有该页面的查询权限");
        return;
      }
      this.$data.isLoad = true;
      const { page, size, keyword } = this.$data;
      const { results, count } = await getUsersData(page, size, keyword);
      this.$data.users = results;
      this.$data.total = count;
      this.$data.isLoad = false;
      recordOperateLog(OperationType.Select);
    },

    formClose(done) {
      this.$confirm("确认关闭？").then(() => {
        done();
      });
    },

    async openUpdateForm(row) {
      const { detail } = await getUserDetail(row.id);
      this.$data.edit.show = true;
      detail.password = "";
      this.$data.edit.target = detail;
    },

    /*
     * 检查表单
     * 通过检查后会触发updateFormSubmit
     */
    checkUpdateForm() {
      this.$refs.updateForm.submit();
    },

    /**
     * 提交修改表单
     */
    async updateFormSubmit() {
      const form = this.$refs.updateForm.data;
      const { status, detail } = await updateUser(form);
      if (status === HTTP_OK) {
        this.$message.success("修改成功");
        this.$data.edit.show = false;
        this.refreshUserList();
        recordOperateLog(OperationType.Update);
      } else {
        this.$message.error("错误:" + detail);
      }
    },

    /*
			打开新增表单
		 */
    openInsertForm() {
      this.$data.addit.target = {
        username: "",
        depid: {},
        mobile: "",
        wxcode: "",
        QQ: "",
        cnname: "",
        llevel: 1,
        remark: "",
        password: "",
      };
      this.$data.addit.show = true;
    },

    /**
     * 检查新增表单
     */
    checkInsertForm() {
      this.$refs.insertForm.submit();
    },

    /**
      新增
    */
    async insertFormSubmit() {
      const form = this.$refs.insertForm.data;
      const { status, detail } = await insertUser(form);
      if (status === HTTP_OK) {
        this.$message.success("新增成功");
        this.$data.addit.show = false;
        this.refreshUserList();
        recordOperateLog(OperationType.Add);
      } else {
        this.$message.error("错误:" + detail);
      }
    },

    /**
     * 删除帐号
     * @param {*} row
     */
    deleteRow(row) {
      this.$confirm(`确认要删除${row.username}这个帐号?`, "提示", {
        type: "warning",
      }).then(async () => {
        this.$data.isLoad = true;
        const { status, detail } = await deleteUser(row.id);
        if (status === HTTP_OK) {
          this.$message.success("删除成功");
          recordOperateLog(OperationType.Delete);
          this.refreshUserList();
        } else {
          this.$message.error("错误:" + detail);
          this.$data.isLoad = false;
        }
      });
    },

    /**
     * 打开详情
     * @param {*} row
     */
    async openDetail(row) {
      const { detail } = await getUserDetail(row.id);
      this.$data.detail.show = true;
      this.$data.detail.target = detail;
      recordOperateLog(OperationType.Detail);
    },

    /**
     * 打开角色
     * @param {*} row
     */
    async openRoleList(row) {
      this.$data.roleList.isLoad = true;
      const { detail } = await getUserRoles(row.id);
      this.$data.roleList.data = detail[0][1] || [];
      this.$data.roleList.isLoad = false;
      recordOperateLog(OperationType.Select, "角色");
    },

    /**
     * 打开用户组
     * @param {*} row
     */
    async openUserGroupList(row) {
      this.$data.groupList.isLoad = true;
      const { detail } = await getUserGroup(row.id);
      this.$data.groupList.data = detail || [];
      this.$data.groupList.isLoad = false;
      recordOperateLog(OperationType.Select, "用户组");
    },

    /**
     * 打开平台表单
     * @param {*} row
     */
    openPlatForm(row) {
      this.$data.platForm.show = true;
      this.$data.platForm.target = row;
    },

    /**
     * 平台选择改变事件
     * @param {*} row
     */
    handleChangePlatSelected(row) {
      this.$data.platForm.selected = row;
    },

    /**
     * 平台选择提交
     */
    async platFormSubmit() {
      const uid = this.$data.platForm.target.id;
      const pid = this.$data.platForm.selected.alarmobjtypeid;
      const { status, detail } = await createPlatUser(uid, pid);
      if (status === HTTP_OK) {
        this.$message.success(detail);
        this.$data.platForm.show = false;
        recordOperateLog(OperationType.Update, "平台");
      } else {
        this.$message.error(detail);
      }
    },

    /**
     * 解锁该行用户
     * @param {*} row
     */
    unlockRow(row) {
      this.$confirm(`确认要解锁${row.username}这个帐号?`, "提示", {
        type: "warning",
      }).then(async () => {
        const { status, detail } = await unlockUser(row.id);
        if (status === HTTP_OK) {
          recordOperateLog(OperationType.Unlock);
          this.$alert(detail, "结果", {
            type: "success",
          });
        } else {
          this.$message.error(detail);
        }
      });
    },
  },
};
</script>

<style>
.container {
  padding-left: 20px;
}
/* 顶行 */
.top-row {
  margin-top: 15px;
}
/* 搜索外部DIV容器 */
.search-container {
  padding-right: 10px;
}

/* 表格行 */
.table-row {
  margin-top: 10px;
}

.table-header {
  background-color: #ddd;
}

/* 角色标签 */
.role-tag {
  margin-right: 5px;
  margin-top: 5px;
}

/* 页数选择外部DIV */
.page-size-container {
  padding-right: 15px;
}

/* 显示总页数外部div*/
.page-total-container {
  padding-top: 7px;
  font-size: 14px;
}

/* 追加eui的对话框样式 */
.el-dialog .el-dialog__body {
  padding-bottom: 0px;
}
</style>
